package com.guozcc.gateway.autofilter.autogobalfilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.slf4j.MDC;
import java.util.UUID;

/**
 * 全局过滤器
 *  这里只是演示一下全局过滤器,对于响应式编程来说，这样使用MDC肯定是不对的，会线程切换，
 */
@Component
public class MdcGlobalFilter implements GlobalFilter, Ordered {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //设置日志追踪索引
        MDC.get("traceId");
        MDC.put("traceId", UUID.randomUUID().toString().replace("-",""));
        log.info("全局过滤器前置执行： "+this.getClass().getSimpleName());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("全局过滤器后置执行： "+this.getClass().getSimpleName());
        }));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
